package tk.xboot.kafka;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Application event to be handle.
 *
 * @author Asin Liu
 * @version 1.0.0
 * @since 1.0.0
 */


@Component
public class ApplicationEventInit {
    Logger log = LoggerFactory.getLogger(ApplicationEventInit.class);

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    private int key;

    @Value("${ws.kfk.topic}")
    private String topic;

    @Value("${ws.loop}")
    private int loop;

    StringBuilder sb;

    @EventListener(ApplicationStartedEvent.class)
    public void run() {
        if (sb == null) {
            sb = new StringBuilder();
            for (int i = 0; i < loop; i++) {
                sb.append("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
                        .append("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
            }
        }
        while (true) {
            String dt = Formatter.format(new Date());
            log.info("While True: The time is now {} counts-store", dt);

            String msg = dt + sb.toString();
            ListenableFuture<SendResult<String, String>> result = kafkaTemplate.send(topic, ++key + "", msg);
        }
    }


}
